import Vue from 'vue'
import { FileDownloader } from '../../../../static/lib/downloader/FileDownloader'
import { SqlLib } from '../../../../static/lib/sqlite/SqlLib'
import { SqlLibUser } from '../../../../static/lib/sqlite/service/SqlLibUser'
import { UserResource } from '../../../../static/lib/sqlite/model/UserResource'
import { UUIDUtil } from '../../../../static/utils/UUIDUtil'
import { SqlLibBook } from '../../../../static/lib/sqlite/service/SqlLibBook'
import resources from '../api/resource'
import usermeta from '@/content/api/usermeta'
import store from '../store/index'
const fs = require('fs')
const path = require('path')
const { dialog } = require('electron').remote

/**
 *@param dom 毕传参数需要遮罩的元素css选择器
 */

let totalBytes = 0
Vue.prototype.$showSaveDialog = (url, dom, lessonName, apiParams) => {
  let loadingInstance = Vue.prototype.$downloadmask(dom)
  dialog.showSaveDialog(
    {
      title: '选择下载位置',
      buttonLabel: '保存',
      defaultPath: lessonName,
      filters: apiParams.format != '' ? 
         [{
          name: apiParams.format.toUpperCase(),
          extensions: [apiParams.format],
        },]: 
        [
            {
                name: 'PDF',
                extensions: ['pdf'],
            },
        ],
    },
    (path) => {
      if (!path) {
        if (loadingInstance) {
          loadingInstance.close()
        }
        return
      }
      resources.createUserDownloadInfoRecord(apiParams).then(res => {
        console.log('教案下载埋点')
      })
      let download = new FileDownloader(url, path)
      let fileSizeCallback = (val) => {
        totalBytes = val
      }
      let progressCallback = (val) => {
        let progress = parseInt((val / (totalBytes * 1024 * 1024)) * 100)
        let maskProgress = new CustomEvent('maskProgress', {
          detail: {
            progress: progress,
          },
        })
        window.dispatchEvent(maskProgress)
      }
      let successCallback = () => {
        //注册下载进度监听事件
        let maskProgress = new CustomEvent('maskProgress', {
          detail: {
            progress: 100,
          },
        })
        window.dispatchEvent(maskProgress)
        loadingInstance.close()
        Vue.prototype.$message.success('下载成功')
      }
      let errorCallback = () => {
        loadingInstance.close()
        Vue.prototype.$message.error('下载失败')
      }
      download.downloadFile(fileSizeCallback, progressCallback, successCallback, errorCallback)
    }
  )
}

Vue.prototype.$showSaveLocalDialog = (params) => {
  const completePath = params.path
  dialog.showSaveDialog(
    {
      title: '选择导出位置',
      buttonLabel: '保存',
      defaultPath: params.name,
      filters: [
        {
          name: 'PPT',
          extensions: ['pptx'],
        },
        {
          name: 'PPT',
          extensions: ['pptx'],
        },
      ],
    },
    (val) => {
      if (!val) return
      fs.access(completePath, (err) => {
        if (err) {
          Vue.prototype.$message.error('导出失败，导出文件不存在')
        } else {
          fs.copyFile(completePath, val, (err) => {
            if (err) {
              Vue.prototype.$message.error('导出失败，请重试')
            } else {
              Vue.prototype.$message.success('导出成功')
            }
          })
        }
      })
    }
  )
}

/**
 *
 * @param  type 导入的资源类型  0-ptt , 1-video
 */
//方法繁琐版本 待优化
Vue.prototype.$showOpenDialog = function (type, uploadParams, uploadCompleted) {
  let _this = this
  dialog.showOpenDialog(
    {
      title: '选择需要导入的文件',
      filters: [
        {
          name: type === 0 ? 'PPT' : '多媒体',
          extensions: type === 0 ? ['ppt', 'pptx',] : ['png', 'jpg', 'jpeg', 'mkv', 'avi', 'mp4','mp3','wav','pdf' , 'doc','docx'],
        }
      ],

      buttonLabel: '导入',
    },
    async (val) => {
        if (!val || val.length === 0) return
        let sqlLib = SqlLib.getInstance(window.$DBDIR)
        let user = SqlLibUser.queryCurrentUser(sqlLib)
        let filePath = val[0]
        // let fileName = filePath.replace(/.*(?=\\)\\/g, '')
        let fileName = path.basename(filePath)
        let fileSize = await getfileSize(filePath)
        console.log('fileSize',fileSize);
        fileName = uploadParams.lessonId + '-' + fileName
        let rootPath = window.$DATADIR
        let index = fileName.lastIndexOf('.')
        let suffixName = fileName.substring(index)
        var pathName = ''
        switch (suffixName) {
            case '.ppt':
                pathName = 'ppt'
                break;
            case '.pptx':
                pathName = 'ppt'
                break;
            case '.pdf':
                pathName = 'pdf'
                break;
            case '.doc':
                pathName = 'word'
                break;
            case '.docx':
                pathName = 'word'
                break;
            case '.png':
                pathName = 'img'
                break;
            case '.jpg':
                pathName = 'img'
                break;
            case '.jpeg':
                pathName = 'img'
                break;
            case '.gif':
                pathName = 'img'
                break;
            case '.bmp':
                pathName = 'img'
                break;
            case '.mp4':
                pathName = 'video'
                break;
            case '.mkv':
                pathName = 'video'
                break;
            case '.avi':
                pathName = 'video'
                break;
            case '.mp3':
                pathName = 'audio'
                break;
            case '.wav':
                pathName = 'audio'
                break;
            default:
                break;
        }
        
        var copyPath = `${rootPath}resc/user/${pathName}/${user.id}/${fileName}/`
        let checkDir = `user/${pathName}/${user.id}`
        // let fMkdir = false
        //循环读取目录没有则创建
        function recursionAccess (checkDir, callBack, fileMd5) {
            let pathArr = checkDir.split('/')
            let checkPath = ''
            pathArr.forEach((v) => {
                checkPath += `/${v}`
                try {
                    fs.accessSync(`${rootPath}resc${checkPath}`)
                    if (checkPath === '/' + checkDir) {
                      upload(fileMd5)
                    }
                } catch (err) {
                    callBack(checkPath)
                }
            })
        }

        function makeDir (mkdirPath) {
            try {
                fs.mkdirSync(`${rootPath}resc${mkdirPath}`)
                if (mkdirPath === '/' + checkDir) {
                    upload()
                }
            } catch (err) {
                console.log(err)
            }
        }

        function getfileSize(filePath) {
            filePath = decodeURI(filePath)
            console.log('filePath',filePath);
            return new Promise((resolve, reject) => {
                if (!filePath) {
                    resolve(0);
                    return
                }
                fs.stat(filePath,(err,data)=>{
                    if (err == null) {
                        resolve(data.size)
                        return
                    }else{
                        resolve(0)
                    }
                })
            })
            
        }
        function upload (fileMd5) {
        fs.access(copyPath, (err) => {
          if (!err) {
            Vue.prototype
              .$dialog({
                title: '提示',
                type: 'warn',
                message: '已存在相同命名文件,是否导入',
                confirm: '取消',
                cancel: '确认',
                close :false
              })
              .then(() => {
                Vue.prototype.$message.success('已取消导入')
              })
                .catch(() => {
                    // Vue.prototype.$message.success('文件已覆盖')
                    console.log(_this.uploadParams);
                    let sameFile = 0
                    let tempName = ''
                    let tName = fileName.split('-')
                    tName.shift()
                    tempName = tName.join('-') 
                    tempName = tempName.substring(0,tempName.lastIndexOf('.'))
                    _this.lessonItems.forEach(item=>{
                        if (item.name.indexOf(tempName) > -1) {
                            console.log('same');
                            sameFile++
                        }
                    })
                    console.log(sameFile);
                    if (sameFile > 0) {
                        let flagIndex = fileName.lastIndexOf('.')
                        let tampName = fileName.substring(0,flagIndex)
                        let suffixName = fileName.substring(flagIndex)
                        fileName = tampName + '(' + (sameFile+1).toString() +')'+ suffixName
                    }
                    console.log(fileName);
                    copyFile(true, fileMd5 , true)
                })
            } else {
                copyFile(true, fileMd5,false)
                Vue.prototype.$message.success('导入文件成功')
            }
        })
        }

      function copyFile (isInsert = true, fileMd5,isSame) {
        try {

            if (isSame) {
                copyPath = `${rootPath}resc/user/${pathName}/${user.id}/${fileName}/`
                console.log(filePath);
            }
            // return
                console.log('复制操作将创建的目标文件名',copyPath);
                fs.copyFileSync(filePath, copyPath)
                if (isInsert) {
                let index = fileName.lastIndexOf('.')
                let suffixName = fileName.substring(index)
                var fileType = ''
                var resType = ''
                switch (suffixName) {
                case '.ppt':
                    fileType = 'selfPpt'
                    break;
                case '.pptx':
                    fileType = 'selfPpt'
                    break;
                case '.pdf':
                    fileType = 'selfPdf'
                    resType = '文档'
                    break;
                case '.doc':
                    fileType = 'selfWord'
                    resType = '文档'
                    break;
                case '.docx':
                    fileType = 'selfWord'
                    resType = '文档'
                    break;
                case '.png':
                    fileType = 'selfImg'
                    resType = '图片'
                    break;
                case '.jpg':
                    fileType = 'selfImg'
                    resType = '图片'
                    break;
                case '.jpeg':
                    fileType = 'selfImg'
                    resType = '图片'
                    break;
                case '.gif':
                    fileType = 'selfImg'
                    resType = '图片'
                    break;
                case '.bmp':
                    fileType = 'selfImg'
                    resType = '图片'
                    break;
                case '.mp4':
                    fileType = 'selfVideo'
                    resType = '视频'
                    break;
                case '.mp3':
                    fileType = 'selfAudio'
                    resType = '音频'
                    break;
                default:
                    break;
                }
                // return
                let user = SqlLibUser.queryCurrentUser(sqlLib)
                let userResource = new UserResource()
                let resourceId = UUIDUtil.uuid()
                let tempFileName = fileName
                let tempNames = tempFileName.split('-')
                tempNames.shift()  // 去除第一个元素lessonID
                tempFileName = tempNames.join('-')  // 将剩下的拼接，防止用户导入的文件名中包含'-'
                let obj = {
                    id: resourceId,
                    userId: user.id,
                    bookId: uploadParams.bookId,
                    lessonId: uploadParams.lessonId,
                    resourceClassify: '0',
                    resourceType: fileType,
                    resourceId: resourceId,
                    resourceName: fileName,
                    downloadStatus: '0',
                    resourceDescription: JSON.stringify({
                      id: resourceId,
                      name: tempFileName,
                      resType: type === 0 ? 'PPT' : resType,
                      fileSize: fileSize,
                      thumb: '',
                      downloadInfo: {
                          FileName: fileName,
                          FileType: fileType,
                          TaskId: resourceId,
                          Url: '',
                      },
                      fileMd5: fileMd5
                    }),
                    isDefault: type === 0 ? '1' : '0',
                }
                    userResource = Object.assign(userResource, obj)
                    console.log(userResource);
                    SqlLibBook.updateOrInsertExtraResource(sqlLib, userResource)
                    if (type === 0) {//设置导入的ppt为默认ppt
                      let result = SqlLibBook.setDefaultPpt(sqlLib, {
                        resourceId: userResource.resourceId,
                        lessonId: uploadParams.lessonId,
                      })
                    }
                    }
                    if (uploadCompleted) {
                      uploadCompleted()
                    }
                } catch (err) {
                  console.log(err)
                  Vue.prototype.$message.error('导入文件失败，请重试')
                }
        }
      const getEtag = require("./qetag");
      const bur = fs.readFileSync(filePath)
      getEtag(bur).then(val => {
        recursionAccess(checkDir, makeDir, val)
      })
    }
  )
}


//删除全书
Vue.prototype.$showDeleteDialog = function(rescDir,menuList){
    console.log(menuList);
    // return
  let _this = this
  Vue.prototype
  .$dialog({
    title: '提示',
    type: 'warn',
    message: '是否删除'+menuList.bookName+'全书',
    confirm: '确认',
    cancel: '取消',
    close :false,
  })
  .then(() => {
    _this.deleteAll = true
    _this.deleteMask = true
    setTimeout(() => {
        deleteZip(rescDir,'.zip')//顺带清楚缓存压缩包
        // let deleteTempArr = JSON.parse(localStorage.downloadedFile)//本地存储的下载记录转对象
        // var deleteArr =[];
        // if (deleteTempArr) {
        // deleteTempArr.forEach((item,v)=>{
        //   if (item.book.bookName === menuList.bookName && item.book.bookId === menuList.bookId) {//找到要删除的课本
        //     deleteArr = item.book
        //     deleteTempArr.splice(v,1)
        //   }
        // })
        // localStorage.removeItem('downloadedFile')
        // localStorage.setItem('downloadedFile', JSON.stringify(deleteTempArr))//删除过后去掉该课本记录
        localStorage.removeItem('downloadedFile')
        var deleteArr =[];
        let sqlLib = SqlLib.getInstance(window.$DBDIR)
        menuList.course.forEach(item => {
            item.lessonVOList.forEach(les=>{
                let lessonResource = SqlLibUser.queryLessonResource(sqlLib, menuList.userId, les.id)
                console.log('lessonResource',lessonResource);
                lessonResource.forEach(val=>{
                    deleteArr.push(val.resourceId)
                })
            })
        });
        // return
        console.log(deleteArr);
        if (deleteArr.length !== 0) {
            console.log('-----------------------删除下载文件');
            deleteArr.forEach((filename,i)=>{
                filename = filename.replace(/[^0-9]/ig,"")
                try {
                    deleteFile(rescDir,filename)
                } catch (error) {
                    console.log('error-------------',error);
                }
                if (i === deleteArr.length -1) {
                    _this.deleteMask = false  //遮罩消失
                    Vue.prototype.$message({
                        type:'success',
                        message:'删除成功',
                        duration:5000,
                    })
                }
            })
        }else{
            _this.deleteMask = false
            Vue.prototype.$message.error('删除失败')
            return
        }   
      console.log('-----------------------删除下载记录');
    //   let sqlLib = SqlLib.getInstance(window.$DBDIR)
      // const user = SqlLibUser.queryCurrentUser(sqlLib)
      // SqlLibBook.deleteAllDownloadedLessonByUserId(SqlLib.getInstance(window.$DBDIR),user.id)  //删除所有下载记录
      menuList.course.forEach(item=>{
        item.lessonVOList.forEach(lesson=>{
          let params = {
            lessonId:lesson.id,
          }
          SqlLibBook.deleteAllLessonInfoByBookId(sqlLib,params)//删除本地数据库中的下载的课程资源
          if (store.state.completedBook) {
            store.state.completedBook.forEach(index=>{
              if (index.lessonId === lesson.id) {
                _this.$store.commit('removeCompletedBook', lesson.id)//移除vuex中已下载课程记录
              }
            })
          }
        })
      })
      
      console.log(store);
      if (_this.menuList.currentLesson !== _this.menuList.course[0].lessonVOList[0].id) {
        _this.menuList.currentLesson = _this.menuList.course[0].lessonVOList[0].id
      }else{
        if (_this.menuList.course[0].lessonVOList[1]) {
          _this.menuList.currentLesson = _this.menuList.course[0].lessonVOList[1].id
        }
      }
      
    }, 1000);
   
  })
  .catch(() => {
    
  })

  function deleteFile(dirPath, filename) {
    let fs = require('fs');//引用Node.js文件系统模块
    var files = [];
    if (fs.existsSync(dirPath)) {
      files = fs.readdirSync(dirPath);
      files.forEach(function (file, index) {
        var curPath = dirPath + "/" + file;
        if (fs.statSync(curPath).isDirectory()) {
          deleteFile(curPath, filename);
        } else {
          if (curPath.indexOf(filename) !== -1) {//找到对应文件夹删除里面所有资源文件
            console.log('删除' + curPath);
            fs.unlinkSync(curPath);
          }
        }
      })
    }
  }

  function deleteZip(dirPath, extname) {
    let fs = require('fs');
    let path = require('path');
    var files = [];
    if (fs.existsSync(dirPath)) {
      files = fs.readdirSync(dirPath);
      files.forEach(function (file, index) {
          var curPath = dirPath + "/" + file;
          if (fs.statSync(curPath).isDirectory()) {
            deleteZip(curPath, extname);
          } else {
              if (path.extname(curPath) === extname) {
                  fs.unlinkSync(curPath);
              }
          }
      })
    }
  }
}
